package dfs;

public class NumberOfClosedIsland_1254 {
    // 与岛屿数量的区别在于，边界的岛屿不算封闭岛屿，因此需要排除边界的岛屿
    private int val = 0;
    public int closedIsland(int[][] grid) {
        // 排除四周的岛屿
        int m = grid.length;
        int n = grid[0].length;
        int res = 0;

        // 最后才是真正遍历岛屿
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 0) {
                    // 正常情况下，val=1，遍历的岛屿算在内
                    val = 1;
                    dfs(grid, i, j, m, n);
                    res += val;
                }
            }
        }
        return res;
    }

    private void dfs(int[][] grid, int i, int j, int m, int n) {
        // 实际上这里就是边界判断，当遍历到边界上的点，可以让val=0，该岛屿不算在内
        if (i >= m || i < 0 || j >= n || j < 0) {
            val = 0;
            return;
        }

        if (grid[i][j] == 1) {
            return;
        }

        // 将遍历过的岛屿变成海水
        grid[i][j] = 1;
        // 从四周开始遍历
        dfs(grid, i+1, j, m, n);
        dfs(grid, i-1, j, m, n);
        dfs(grid, i, j+1, m, n);
        dfs(grid, i, j-1, m, n);
    }
}
